<template>
  <div class="app-container">
    <el-col :span="13">
      <el-col :span="5">
        <el-tag color="white">门诊医技工作台</el-tag>
      </el-col>
      <el-col :span="14" :offset="1">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item prop="name">
            <el-input
              v-model="queryParams.keyword"
              placeholder="病历号/姓名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-col>

      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>

    <el-table v-loading="loading" :data="non_drug_item_recordList" @selection-change="handleSelectionChange">
      <el-table-column label="病历号" align="center" prop="patient.medicalRecordNo" />
      <el-table-column label="姓名" align="center" prop="patient.name" />
      <el-table-column label="年龄" align="center" prop="registration.patientAgeStr" />
      <el-table-column label="性别" align="center" prop="patient.gender" >
      <template slot-scope="scope">
        {{formatIfPass[scope.row.patient.gender]}}
      </template>
      </el-table-column>
      <el-table-column label="开立项目" align="center" prop="nonDrug.name" />
      <el-table-column label="检查部位" align="center" prop="checkParts" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
        <el-tag :type='onColourLine[scope.row.status]'>{{onLine[scope.row.status]}}</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status!=3"
            v-hasPermi="['dms:non_drug_item_record:edit']"
          >登记</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status!=3"
            v-hasPermi="['dms:non_drug_item_record:remove']"
          >补录</el-button>
          <el-button
            type="primary"
            size="small"
            v-if="scope.row.status==3"
            @click="handleAddCheckResult(scope.row)"
            v-hasPermi="['dms:non_drug_item_record:edit']"
          >上传结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检查项检验项处置项记录(开立的)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="检查结果">
          <el-input v-model="form.checkResult" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <el-dialog :visible.sync="isShow" append-to-body>
        <el-upload
          title="点击上传文件"
          :action="ossHost"
          :data="ossData"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="beforeUpload">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-dialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" size="mini" icon="el-icon-upload" @click="cancel">上传图片</el-button>
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNon_drug_item_record, getNon_drug_item_record, delNon_drug_item_record, addNon_drug_item_record, updateNon_drug_item_record, exportNon_drug_item_record, updateNon_drug_item_record_check_result } from "@/api/dms/non_drug_item_record";
import {policy} from '@/api/upload'
// 导入uuid库
import uuidv4 from 'uuid/v4'

export default {
  name: "Non_drug_item_record",
  data() {
    return {
      isShow: false,
      dialogImageUrl: '',
      dialogVisible: false,
      ossHost: '',
      ossData: {},
      // 状态的对应的值
      onLine: {"0": "作废", "1": "未缴费", "2": "未登记", "3": "已登记", "4":"已执行", "5":"已退费", "6":"已过期"},
      // 状态的对应的颜色
      onColourLine: {"0": "warning", "1": "success", "2": "info", "3": "", "4":"", "5":"", "6":"warning"},
      //性别
      formatIfPass: {
        "0": "女", "1": "男",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检查项检验项处置项记录(开立的)表格数据
      non_drug_item_recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
 /*  watch: {
    // 监听姓名查询参数的变化
    'queryParams.name'(val) {
      // 将值赋给 病历号
      this.queryParams.medicalRecordNo = val;
    },
  },*/
  methods: {
    /** 查询检查项检验项处置项记录(开立的)列表 */
    getList() {
      this.loading = true;
      listNon_drug_item_record(this.queryParams).then(response => {
        this.non_drug_item_recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isShow = true;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registrationId: null,
        status: 0,
        aim: null,
        demand: null,
        logStatus: 0,
        checkResult: null,
        resultImgUrlList: null,
        clinicalImpression: null,
        clinicalDiagnosis: null,
        createTime: null,
        excuteStaffId: null,
        logDatetime: null,
        noDrugId: null,
        checkParts: null,
        type: null,
        excuteDeptId: null,
        createStaffId: null,
        logStaffId: null,
        excuteTime: null,
        amount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检查项检验项处置项记录(开立的)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getNon_drug_item_record(id).then(response => {
        this.form = response.data;
        this.$confirm('确定为 "' + this.form.patient.name + '"登记项目"'+this.form.nonDrug.name+'"吗?', "项目登记", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.form.status=3;
          updateNon_drug_item_record(this.form).then(response =>{
            if (response.code === 200) {
              this.msgSuccess("登记成功");
              this.getList();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消登记'
          });
        });
      });
    },
    /** 新增检查结果按钮操作 */
    handleAddCheckResult(row) {
      this.reset();
      this.form.id=row.id;
      this.form.status= 4;
      this.open = true;
      this.title = "结果";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateNon_drug_item_record_check_result(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addNon_drug_item_record(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除检查项检验项处置项记录(开立的)编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delNon_drug_item_record(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有检查项检验项处置项记录(开立的)数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportNon_drug_item_record(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleSuccess(response, file, fileList) {
      console.log(this.ossData.key);
      // 将文件名保存到数据库
      if(this.form.resultImgUrlList!=undefined||this.form.resultImgUrlList!=null){
        this.form.resultImgUrlList += ","+this.ossData.key;
      }else{
        this.form.resultImgUrlList = this.ossData.key;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      // element ui upload需要一个promise对象
      return new Promise(resolve => {
        return this.getSign().then(data => {
          const suffix = file.name.substring(file.name.lastIndexOf("."))
          this.ossHost = data.host
          // 注意参数的大小写，oss文档就是这样定义的
          // 跟后端返回的变量名不一样，所以只能手动赋值
          this.ossData = {
            key: data.dir + uuidv4() + suffix,
            policy: data.policy,
            OSSAccessKeyId: data.accessKeyId,
            success_action_status: '200', //让服务端返回200，不设置则默认返回204。
            callback: data.callbackBody,
            signature: data.signature,
            expire: data.expire
          }
          resolve(true)
        })
      })
    },
    getSign() {
      // 因为获取签名的方法是异步的，所以通过promise对象执行签名过期判断
      // 确保异步方法执行完成后再执行then中的逻辑，否则可能获取不到值
      return new Promise(resolve => {
        // 判断签名有没有过期，过期了就重新获取签名
        let sign = JSON.parse(sessionStorage.getItem("hncc-oss-sign"));
        let timestamp = Date.parse(new Date()) / 1000;
        if (sign && sign.expire - 3 > timestamp) {
          resolve(sign);
        } else {
          // 重新获取签名并保存
          policy().then(response => {
            sessionStorage.setItem("hncc-oss-sign", JSON.stringify(response.data));
            resolve(response.data);
          });
        }
      })
    }
  }
};
</script>
